package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConst;
import com.itheima.entity.Result;
import com.itheima.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

	@Reference
	private UserService userService;

	@RequestMapping("/getUsername")
	public Result getUsername(){
		log.debug("获取用户名!!");
		//获取安全框架上下文对象
		SecurityContext context = SecurityContextHolder.getContext();
		//获取认证对象
		Authentication authentication = context.getAuthentication();
		//获取 Principal 重要对象
		Object principal = authentication.getPrincipal();
		if(principal instanceof User){
			User user = (User) principal;
			String username = user.getUsername();
			return new Result(true, MessageConst.GET_USERNAME_SUCCESS, username);
		}
		return new Result(false,MessageConst.GET_USERNAME_FAIL);
	}

	@RequestMapping("/loginSuccess")
	public ModelAndView loginSuccess(){
		return new ModelAndView("redirect:http://oms.web.health:83/pages/main.html");
	}

	@RequestMapping("/loginError")
	public ModelAndView doError(){
		return new ModelAndView("redirect:http://oms.web.health:83/login.html");
	}

//	@RequestMapping("/login")
//	public Result login(String username, String password){
//		log.debug("oms backend,user:"+username+" ,password:"+password);
//		if(userService.login(username,password)){
//			log.debug("login ok!!!");
//			return new Result(true, MessageConst.ACTION_SUCCESS);
//		}else{
//			log.debug("login fail");
//			return new Result(false,MessageConst.ACTION_FAIL);
//		}
//	}
}